<?php

namespace app\controller\admin;

use laytp\BaseController;
use think\facade\Db;


/**
 * 处理图片控制器
 */
class Image extends BaseController
{
    //关键词次数和图片后缀
    private static $key_number = [
        'url' => [
            'number' => 0,
            'image' => ''
        ],
        'icon' => [
            'number' => 0,
            'image' => ''
        ],
        'picture' => [
            'number' => 0,
            'image' => ''
        ],
        'avatar' => [
            'number' => 0,
            'image' => ''
        ],
        'imgs' => [
            'number' => 0,
            'image' => ''
        ],
    ];
    //模块对应的主域名
    private static $module = [
        'sgz' => "https://static.g.mi.com/game/game-tools/assets/img/honor-of-kings",
    ];
    //本地相对路径
    private static $dir = "./temp_image/";

    private $database_name = "xm_game_test";

    public function saveDatabaseImg()
    {
        try {
            $module = array_keys(self::$module);
            $result = Db::query("SELECT table_name FROM information_schema.tables where table_schema = '" . $this->database_name . "'");
            ignore_user_abort(true);
            set_time_limit(0);
            $modules = [];
            foreach ($result as &$item) {
                $item = array_slice(explode("_", $item['table_name']), 1);
                if (isset($item[0])) {
                    if (in_array($item[0], $module)) {
                        $modules[$item[0]][] = [
                            'table_name' => implode("_", $item),
                            'dir_name' => self::$dir . $item[0] . "/" . implode('_', array_slice($item, 1)),
                        ];
                    }
                }
            }
            $imgs = [];
            foreach ($modules as $k => $items) {
                $sql = "set @domain  =  '" . self::$module[$k] . "';" . "\r\n";
                $sql .= "set @oldmain  =  'http://agent-1.oss-cn-beijing.aliyuncs.com';" . "\r\n";
                foreach ($items as $item) {
                    $list = Db::name($item['table_name'])->select();
                    $key_number = self::$key_number;
                    $keyword = array_keys($key_number);
                    foreach ($list as $value) {
                        if (isset($value['delete_time']) && !empty($value['delete_time'])) {
                            continue;
                        }
                        foreach ($keyword as $i) {
                            if (isset($value[$i])) {
                                if ($key_number[$i]['number'] == 0) {
                                    $key_number[$i]['image'] = "." . explode('.', $value[$i])[count(explode('.', $value[$i])) - 1];
                                }
                                $key_number[$i]['number'] = 1;
                                $temp = $item['dir_name'] . "/" . $i;
                                if (!is_dir($temp)) {
                                    mkdir($temp, 0777, true);
                                }
                                if ($i == "imgs") {
                                    $list = explode(",", $value[$i]);
                                    foreach ($list as $img) {
                                        $imgs[] = $img;
//                                        $this->downloadImage($img,$temp."/".explode('/',$img)[count(explode('/',$img))-1]);
                                    }
                                } else {
//                                    $this->downloadImage($value[$i],$temp."/".explode('/',$value[$i])[count(explode('/',$value[$i]))-1]);
                                }
                                //下载图片
                            }
                        }
                    }
                    foreach ($key_number as $name => $i) {
                        if ($i['number'] > 0) {
                            $sql .= "update lt_" . $item['table_name'] . " set `" . $name . "` REPLACE(`" . $name . "`,@oldmain,@domain)" . "\r\n";
                        }
                    }
                    $file = fopen("./temp_image/" . $k . "/" . $k . ".sql", "w");
                    fwrite($file, $sql);
                    fclose($file);
                }
            }
            foreach ($imgs as $img) {
                $this->downloadImage($img,  "./temp_image/team/" . explode('/', $img)[count(explode('/', $img)) - 1]);
//                dd(1);
            }
            dd($imgs);
        } catch (\Exception $exception) {
            dd($exception->getMessage());
        }

    }

    public function nameImg(){
        $list = Db::name("sgz_team")->select()->toArray();
        foreach ($list as $item){
            $item['imgs'] = explode(",",$item['imgs']);
            $imgs = [];
            dd($i);
            for($i=1;$i<=count($item['imgs']);$i++){
                if(count($item['imgs'])==1){
                    $imgs[] ="https://agent-1.oss-cn-beijing.aliyuncs.com/xm_game/sgz/team/20221230/".$item['id'].".png";
                }else{
                    $imgs[] ="https://agent-1.oss-cn-beijing.aliyuncs.com/xm_game/sgz/team/20221230/".$item['id']."-".$i.".png";
                }
                $item['imgs'] = implode(",",$imgs);
            }
        }
        dd($list);
    }

    //下载图片
    private function downloadImage($url, $filename = '/temp_image/')
    {
        value($url);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, '0');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, '0');
        $file = curl_exec($ch);
        curl_close($ch);
        if($file){
            $resource = fopen($filename, 'wb');
            fwrite($resource, $file);
            // 检查写入操作是否已完成
            $streamMetadata = stream_get_meta_data($resource);
            while (!feof($resource) && $streamMetadata['unread_bytes'] > 0) {
                // 等待一段时间再进行检查
                usleep(100000); // 100毫秒

                // 更新流的元数据
                $streamMetadata = stream_get_meta_data($resource);
            }
            fclose($resource);
        }
        return $filename;
    }
}

